package com.npy.reggie.service.Imlp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.npy.reggie.doman.Category;
import com.npy.reggie.doman.Dish;
import com.npy.reggie.doman.DishFlavor;
import com.npy.reggie.dto.DishDto;
import com.npy.reggie.mapper.CategoryMapper;
import com.npy.reggie.mapper.DishMapper;
import com.npy.reggie.service.CategoryService;
import com.npy.reggie.service.DishFlavorService;
import com.npy.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        save(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors=flavors.stream().map(item->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {

       updateById(dishDto);

        QueryWrapper<DishFlavor> queryWrapper= new QueryWrapper<>();

        queryWrapper.lambda().eq(dishDto.getId()!=null,DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        dishFlavorService.saveBatch(dishDto.getFlavors().stream().map(itme->{
            itme.setDishId(dishDto.getId());
            return itme;
        }).collect(Collectors.toList()));
    }
}
